const router = require('express').Router();
const cateModel = require('../models/cate');

router.get('/cateList',async (req,res)=>{
    let { current=1,pageSize=4 } = req.query;
    current = current - 0;
    pageSize = pageSize - 0;
    const result = await cateModel.find().limit(pageSize).skip((current-1)*pageSize).sort({
        _id:-1
    });
    const count = await cateModel.count();
    res.render('cateList',{
        cates:result,
        count,
        current
    })
})
router.get('/cateAdd',(req,res)=>{
    cateModel.find().then(ret=>{
        res.render('cateAdd',{
            cates: ret
        })
    }).catch(err=>{
        res.render('cateAdd',{
            cates:[]
        })
    })
    
})
router.get('/cateEdit',async (req,res)=>{
    const{ id } = req.query
    const cates =  await cateModel.find();
    const cate = await cateModel.findOne({
        _id: id
    })
    res.render('cateEdit',{
        cates,
        cate
    })
})
router.post('/cateEdit',(req,res)=>{
    cateModel.update({
        _id: req.body._id},
        req.body
    ).then(ret=>{
        res.send({
            code:0,   //接口有无问题  状态码
            msg:'修改成功',
        })
    }).catch(err=>{
        res.send({
            code:-1,   //接口有无问题  状态码
            msg:'增加失败',
        })
    })
})

router.post('/cateAdd',(req,res)=>{
    cateModel.insertMany(req.body).then(ret=>{
        res.send({
            code:0,   //接口有无问题  状态码
            msg:'增加成功',
        })
    }).catch(err=>{
        res.send({
            code:-1,   //接口有无问题  状态码
            msg:'增加失败',
        })
    })
    
})

router.post('/cateDel',(req,res)=>{
    const { _id } = req.body;
    cateModel.remove({
        _id
    }).then(ret=>{
        res.send({
            code:0,
            msg:'删除成功'
        })
    }).catch(err=>{
        res.send({
            code:-1,
            msg:'删除失败'
        })
    })
})

module.exports = router;